package com.tim.app.ui.view;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.VerticalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Story;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.StoryListResult;
import com.tim.app.server.result.UserFollowResult;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.activity.person_center.SomeOneDynamicActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneAnswerActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneArticleActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneQuestionActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneStoryActivity;
import com.tim.app.ui.activity.some_homepage.UserListActivity;
import com.tim.app.ui.adapter.someone_homepage.AlbumAdapter;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewActivity;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewTopicActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页的header
 */

public class SomeOneHomepageHeadView extends LinearLayout implements View.OnClickListener, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "SomeOneHomepageHeadView";
    private TextView tvAnswerCount;//回答数量
    private TextView tvDynmaicCount;//动态数量
    private TextView tvQuestionCount;//问题数量
    private TextView tvArticleCount;//文章数量

    private LinearLayout llAnswer;
    private LinearLayout llDynamic;
    private LinearLayout llQuestion;
    private LinearLayout llArticle;

    private LinearLayout llLeft;
    private LinearLayout llRight;

    private TextView tvFollowNumber;
    private TextView tvFansNumber;
    private LinearLayout llPriseContainer;
    private View vContainer;


    private TextView tvDynamicTitle;
    private LinearLayout llId;
    private TextView tvID;
    private LinearLayout llFollower;
    private TextView tvFollower;
    private LinearLayout llConstellation;
    private TextView tvConstellation;
    private LinearLayout llEmotionalState;
    private TextView tvEmotionalState;
    private LinearLayout llResident;
    private TextView tvResident;
    private LinearLayout llHeight;
    private TextView tvHeight;
    private LinearLayout llWeight;
    private TextView tvWeight;

    private TextView tvUserInfo;//性别控制
    private TextView tvSomeoneStory;//某人的故事，性别控制
    private TextView tvAllStory;//全部故事

    private TextView tvHasNoPhoto;
    private WrapRecyclerView wrvAlbum;
    private AlbumAdapter adapter;
    private List<String> dataList;

    private String dynamicPrompt = "";
    private String infoPrompt = "";
    private String storyPrompt = "";
    private String photoPrompt = "";
    private String noPhotoPrompt = "";
    private String noStoryPrompt = "";

    private TextView tvHasNoStory;
    private LinearLayout llStoryContainer;
    private RelativeLayout rlStoryOne;
    private RoundedImageView rivCover;
    private TextView tvTitle;
    private RelativeLayout rlStoryTwo;
    private RoundedImageView rivCoverTwo;
    private TextView tvTitleTwo;

    private TextView tvSomeonePhoto;

    public SomeOneHomepageHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        tvAnswerCount = (TextView) findViewById(R.id.tvAnswerCount);
        tvDynmaicCount = (TextView) findViewById(R.id.tvDynmaicCount);
        tvQuestionCount = (TextView) findViewById(R.id.tvQuestionCount);
        tvArticleCount = (TextView) findViewById(R.id.tvArticleCount);

        llAnswer = (LinearLayout) findViewById(R.id.llAnswer);
        llDynamic = (LinearLayout) findViewById(R.id.llDynamic);
        llQuestion = (LinearLayout) findViewById(R.id.llQuestion);
        llArticle = (LinearLayout) findViewById(R.id.llArticle);

        tvFollowNumber = (TextView) findViewById(R.id.tvFollowNumber);
        tvFansNumber = (TextView) findViewById(R.id.tvFansNumber);
        llPriseContainer = (LinearLayout) findViewById(R.id.llPriseContainer);
        vContainer = findViewById(R.id.vContainer);
        llLeft = (LinearLayout) findViewById(R.id.llLeft);
        llRight = (LinearLayout) findViewById(R.id.llRight);

        llId = (LinearLayout) findViewById(R.id.llId);
        tvID = (TextView) findViewById(R.id.tvID);
        llConstellation = (LinearLayout) findViewById(R.id.llConstellation);
        tvConstellation = (TextView) findViewById(R.id.tvConstellation);
        llFollower = (LinearLayout) findViewById(R.id.llFollower);
        tvFollower = (TextView) findViewById(R.id.tvFollower);
        llEmotionalState = (LinearLayout) findViewById(R.id.llEmotionalState);
        tvEmotionalState = (TextView) findViewById(R.id.tvEmotionalState);
        llResident = (LinearLayout) findViewById(R.id.llResident);
        tvResident = (TextView) findViewById(R.id.tvResident);
        llHeight = (LinearLayout) findViewById(R.id.llHeight);
        tvHeight = (TextView) findViewById(R.id.tvHeight);
        llWeight = (LinearLayout) findViewById(R.id.llWeight);
        tvWeight = (TextView) findViewById(R.id.tvWeight);

        tvSomeonePhoto = (TextView) findViewById(R.id.tvSomeonePhoto);
        tvUserInfo = (TextView) findViewById(R.id.tvUserInfo);
        tvSomeoneStory = (TextView) findViewById(R.id.tvSomeoneStory);
        tvAllStory = (TextView) findViewById(R.id.tvAllStory);

        tvHasNoPhoto = (TextView) findViewById(R.id.tvHasNoPhoto);
        wrvAlbum = (WrapRecyclerView) findViewById(R.id.wrvAlbum);
        wrvAlbum.setOverScrollMode(View.OVER_SCROLL_NEVER);
        tvDynamicTitle = (TextView) findViewById(R.id.tvDynamicTitle);

        tvHasNoStory = (TextView) findViewById(R.id.tvHasNoStory);
        llStoryContainer = (LinearLayout) findViewById(R.id.llStoryContainer);
        rlStoryOne = (RelativeLayout) findViewById(R.id.rlStoryOne);
        rivCover = (RoundedImageView) findViewById(R.id.rivCover);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        rlStoryTwo = (RelativeLayout) findViewById(R.id.rlStoryTwo);
        rivCoverTwo = (RoundedImageView) findViewById(R.id.rivCoverTwo);
        tvTitleTwo = (TextView) findViewById(R.id.tvTitleTwo);

        int width = (int) (RT.getScreenWidth() - (RT.getDensity() * 19)) / 2;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width / 2);
        rlStoryOne.setLayoutParams(params);
        rlStoryTwo.setLayoutParams(params);

        llAnswer.setOnClickListener(this);
        llDynamic.setOnClickListener(this);
        llQuestion.setOnClickListener(this);
        llArticle.setOnClickListener(this);
        llLeft.setOnClickListener(this);
        llRight.setOnClickListener(this);
        llPriseContainer.setOnClickListener(this);
        vContainer.setOnClickListener(this);
        tvAllStory.setOnClickListener(this);
        rlStoryOne.setOnClickListener(this);
        rlStoryTwo.setOnClickListener(this);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        storyList = new ArrayList<>();

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        wrvAlbum.setLayoutManager(layoutManager);

        View headerView = new View(getContext());
        headerView.setLayoutParams(new RecyclerView.LayoutParams((int) RT.getDensity() * 9, RecyclerView.LayoutParams.MATCH_PARENT));
        headerView.setBackgroundColor(getContext().getResources().getColor(R.color.transparent));
        wrvAlbum.addHeaderView(headerView);
        wrvAlbum.addItemDecoration(new VerticalDividerItemDecoration.Builder(getContext()).color(getResources().getColor(R.color.transparent)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());
        adapter = new AlbumAdapter(getContext(), dataList);
        adapter.setOnItemClickListener(this);
        wrvAlbum.setAdapter(adapter);
    }

    /**
     * 根据用户初始化默认信息
     *
     * @param user
     */
    private void initInfoBySex(User user) {
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(user.getUserId())) {
            infoPrompt = "我的资料";
            storyPrompt = "我的故事";
            photoPrompt = "我的照片";
            noStoryPrompt = "你还没有发布故事";
            dynamicPrompt = "我的动态";
        } else {
            if (user.getSex() == 1) {
                infoPrompt = "他的资料";
                noStoryPrompt = "他还没有发布故事";
                storyPrompt = "他的故事";
                photoPrompt = "他的照片";
                noPhotoPrompt = "他还没有上传照片";
                dynamicPrompt = "他的动态";
            } else {
                infoPrompt = "她的资料";
                noStoryPrompt = "她还没有发布故事";
                storyPrompt = "她的故事";
                photoPrompt = "她的照片";
                noPhotoPrompt = "她还没有上传照片";
                dynamicPrompt = "她的动态";
            }
        }
        tvDynamicTitle.setText(dynamicPrompt);
        tvUserInfo.setText(infoPrompt);
        tvSomeoneStory.setText(storyPrompt);
        tvSomeonePhoto.setText(photoPrompt);
        tvHasNoPhoto.setText(noPhotoPrompt);
    }

    /**
     * 请求故事列表
     */
    private void getSomeOneStory(String userId) {
        API_Found.ins().getSomeonStoryList(TAG, userId, 1, 5, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    StoryListResult result = new Gson().fromJson(resultValue, StoryListResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            if (result.getRes().getArraylist().getResult().size() > 2) {
                                tvAllStory.setVisibility(View.VISIBLE);
                            } else {
                                tvAllStory.setVisibility(View.GONE);
                            }
                            showStory(result.getRes().getArraylist().getResult());
                        } else {
                            updateStoryUi(null);
                        }
                    } else {
                        updateStoryUi(null);
                    }
                } else {
                    updateStoryUi(null);
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    private ArrayList<Story> storyList;

    private void showStory(List<Story> list) {
        updateStoryUi(list);
        storyList.clear();
        storyList.addAll(list);
        if (null == list || list.size() == 0) {
            return;
        }
        if (list.size() == 1) {
            rlStoryOne.setVisibility(View.VISIBLE);
            rlStoryTwo.setVisibility(View.GONE);
            tvTitle.setText(list.get(0).getTitle());
            BitmapLoader.ins().loadImage(list.get(0).getImage(), rivCover);
        } else {
            rlStoryOne.setVisibility(View.VISIBLE);
            rlStoryTwo.setVisibility(View.VISIBLE);
            tvTitle.setText(list.get(0).getTitle());
            tvTitleTwo.setText(list.get(1).getTitle());
            BitmapLoader.ins().loadImage(list.get(0).getImage(), rivCover);
            BitmapLoader.ins().loadImage(list.get(1).getImage(), rivCoverTwo);
        }

    }

    private void updateStoryUi(List<Story> list) {
        if (null == list || list.size() == 0) {
            tvHasNoStory.setVisibility(View.VISIBLE);
            llStoryContainer.setVisibility(View.GONE);
            tvAllStory.setVisibility(View.GONE);
            tvHasNoStory.setText(noStoryPrompt);
        } else {
            tvHasNoStory.setVisibility(View.GONE);
            llStoryContainer.setVisibility(View.VISIBLE);
        }
    }

    public void setSelfImage(List<String> list) {
        dataList.clear();
        dataList.addAll(list);
        adapter.notifyDataSetChanged();
    }

    public void setOtherSImage(List<String> list) {
        if (null == list || list.size() == 0) {
            tvHasNoPhoto.setVisibility(View.VISIBLE);
            wrvAlbum.setVisibility(View.GONE);
        } else {
            tvHasNoPhoto.setVisibility(View.GONE);
            wrvAlbum.setVisibility(View.VISIBLE);
            dataList.clear();
            dataList.addAll(list);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取关注的用户
     *
     * @param userId
     */
    private void getFollowUser(String userId) {
        API_User.ins().getFollowUser(TAG, userId, 1, 5, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    UserFollowResult result = new Gson().fromJson(resultValue, UserFollowResult.class);

                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            llPriseContainer.removeAllViews();
                            for (int i = 0; i < result.getRes().getArraylist().getResult().size(); i++) {
                                RoundedImageView roundedImageView = new RoundedImageView(getContext());
                                final User currentValue = result.getRes().getArraylist().getResult().get(i).getUserMsg();
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) RT.getDensity() * 30, (int) RT.getDensity() * 30);
                                if (i != 0) {
                                    params.setMargins(-(int) RT.getDensity() * 7, 0, 0, 0);
                                }
                                roundedImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                roundedImageView.setLayoutParams(params);
                                roundedImageView.setBorderColor(getResources().getColor(R.color.white));
                                roundedImageView.setBorderWidth(1f);
                                roundedImageView.setOval(true);
                                if (null != currentValue && !TextUtils.isEmpty(currentValue.getImage())) {
                                    BitmapLoader.ins().loadImage(currentValue.getImage(), roundedImageView);
                                } else {
                                    BitmapLoader.ins().loadImage(currentValue.getImage(), roundedImageView);
                                }
                                llPriseContainer.addView(roundedImageView);
                            }
                        }
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    User currentUser;

    /**
     * 刷新页面
     *
     * @param user
     */
    public void setData(final User user) {
        if (null == user)
            return;
        currentUser = user;
        initInfoBySex(user);
        tvAnswerCount.setText(String.valueOf(user.getAnswerCount()));
        tvDynmaicCount.setText(String.valueOf(user.getSpeakCount()));
        tvArticleCount.setText(String.valueOf(user.getPublishCount()));
        tvQuestionCount.setText(String.valueOf(user.getProblemCount()));
        tvFollowNumber.setText(String.valueOf(user.getUserConsernCount()));
        tvFansNumber.setText(String.valueOf(user.getConcernUserCount()));
        if (!TextUtils.isEmpty(user.getUuid())) {
            tvID.setText(user.getUuid());
        }
        if (!TextUtils.isEmpty(user.getAddress())) {
            tvResident.setText(user.getAddress());
        } else {
            llResident.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(user.getConstellation())) {
            tvConstellation.setText(user.getConstellation());
        } else {
            llConstellation.setVisibility(View.GONE);
        }
        tvFollower.setText(user.getFlowerCount() + "个");
        llEmotionalState.setVisibility(View.GONE);
        llHeight.setVisibility(View.GONE);
        llWeight.setVisibility(View.GONE);
        getFollowUser(user.getUserId());
        getSomeOneStory(user.getUserId());
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        String value = dataList.get(position);
        if (value.equals(AppKey.ADD_PIC)) {
            EventManager.ins().sendEvent(EventTag.ADD_ABLUM, 0, 0, null);
        } else {
            String lastImage = dataList.get(dataList.size() - 1);
            int total = dataList.size();
            if (lastImage.equals(AppKey.ADD_PIC)) {
                total = dataList.size() - 1;
            }
            ArrayList<ImageItem> images = new ArrayList<>();
            for (int i = 0; i < total; i++) {
                ImageItem imageItem = new ImageItem();
                imageItem.url = dataList.get(i);
                imageItem.isFromNet = true;
                images.add(imageItem);
            }
            Intent intent = new Intent(getContext(), ImagePreviewTopicActivity.class);
            intent.putExtra(ImagePickerManager.EXTRA_SELECTED_IMAGE_POSITION, position);
            intent.putExtra(ImagePickerManager.EXTRA_IMAGE_ITEMS, images);
            if (UserManager.ins().isLogin() && currentUser.getUserId().equals(UserManager.ins().getUserId())) {
                intent.putExtra(ImagePreviewTopicActivity.IS_DELETE, true);
            }
            intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
            getContext().startActivity(intent);  //如果是多选，点击图片进入预览界面
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llAnswer:
                SomeoneAnswerActivity.start(getContext(), currentUser);
                break;
            case R.id.llDynamic:
                SomeOneDynamicActivity.start(getContext(), currentUser, true);
                break;
            case R.id.llQuestion:
                SomeoneQuestionActivity.start(getContext(), currentUser);
                break;
            case R.id.llArticle:
                SomeoneArticleActivity.start(getContext(), currentUser);
                break;
            case R.id.llLeft:
            case R.id.llPriseContainer:
            case R.id.vContainer:
                UserListActivity.start(getContext(), currentUser, 0);
                break;
            case R.id.llRight:
                UserListActivity.start(getContext(), currentUser, 1);
                break;
            case R.id.tvAllStory:
                SomeoneStoryActivity.start(getContext(), currentUser);
                break;
            case R.id.rlStoryOne:
                if (null != storyList && storyList.size() > 0) {
                    StoryDetailActivity.start(getContext(), storyList, 0, false);
                }
                break;
            case R.id.rlStoryTwo:
                if (null != storyList && storyList.size() > 0) {
                    StoryDetailActivity.start(getContext(), storyList, 1, false);
                }
                break;
        }
    }


}
